<template>
  <a-layout >
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-button type="primary" @click="add" style="margin-bottom: 20px">添加</a-button>
      <a-table :dataSource="contentList"
               :columns="columns"
               :pagination="pagination"
               :loading="Loading"
               @change="handleTableChange"
      >
        <template #pic="{text}">
            <a-image :src="text" style="height: 100px"/>
        </template>

        <template #status="{text}">
          {{text==1?"有效":"无效"}}
        </template>

        <template v-slot:action="{text,record}">
          <a-button type="primary" @click="edit(record)">编辑</a-button>
          <a-popconfirm
              title="删除后无法恢复，确认删除?"
              ok-text="是"
              cancel-text="否"
              @confirm="del(record.id)"
          >
            <a-button type="danger">删除</a-button>
          </a-popconfirm>

        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal v-model:visible="modelVisible"
           title="品牌编辑表单"
           cancel-text="取消"
           @cancel="cancel"
           ok-text="确定"
           @ok="handleModelOk">
    <a-form
        :model="content"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="内容类目ID">
        <a-select
            v-model:value="content.categoryId"
        >
          <a-select-option v-for="item in contentCategoryList"
                           :key="item.id"
                           :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="内容标题">
        <a-input v-model:value="content.title" />
      </a-form-item>

      <a-form-item label="链接">
        <a-input v-model:value="content.url" />
      </a-form-item>

      <a-form-item label="图片">

        <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="true"
            :action="actionImg"
            :before-upload="beforeUpload"
            @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100px; height: 80px;"/>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">文件上传</div>
          </div>

        </a-upload>

      </a-form-item>

      <a-form-item label="状态">
        <a-checkbox v-model:value="checked" v-model:checked="checked"></a-checkbox>
      </a-form-item>

      <a-form-item label="排序">
        <a-input v-model:value="content.sortOrder" />
      </a-form-item>


    </a-form>
  </a-modal>
</template>

<script lang="ts">
import{ref,onMounted} from "vue";
import axios from "axios";
import {Tool} from "@/util/tool";
import {message, UploadChangeParam, UploadProps} from "ant-design-vue";
import { PlusOutlined } from '@ant-design/icons-vue';
export default {
  name: "admin-content",

  setup: function () {
    const contentList = ref();
    const Loading = ref<boolean>(false);
    const modelVisible = ref<boolean>(false);
    const checked = ref<boolean>(false);
    const content = ref();
    const contentCategoryList = ref([]);
    const fileList = ref([]);
    const imageUrl = ref<string>('');
    const actionImg = ref('http://localhost:8878/uploadFile');
    // const actionImg = ref('https://www.mocky.io/v2/5cc8019d300000980a055e76');
    const pagination = ref({
      current: 1,
      pageSize: 5,
      total: 0
    });


    const columns = [
      {
        title: '内容ID',
        dataIndex: 'id',
        key: 'id',

      },
      {
        title: '内容类目ID',
        dataIndex: 'categoryId',
        key: 'categoryId',

      },
      {
        title: '内容标题',
        dataIndex: 'title',
        key: 'title',

      },
      {
        title: '链接',
        dataIndex: 'url',
        key: 'url',

      },
      {
        title: '图片',
        key: 'pic',
        dataIndex: 'pic',
        slots: {customRender: 'pic'},

      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        slots: {customRender: 'status'},
      },
      {
        title: '排序',
        dataIndex: 'sortOrder',
        key: 'sortOrder',

      },
      {
        title: '操作',
        key: 'action',
        dataIndex: 'action',
        slots: {customRender: 'action'},
      }
    ];

    const handleQueryContentList = (params: any) => {
      Loading.value = true;
      axios.get('/mall-content/content-Ms/ContentListByPage', {
        params: {
          page: params.page,
          size: params.size
        }
      }).then((response) => {
        Loading.value = false;
        contentList.value = response.data.list;

        //重置分页按钮
        pagination.value.current = params.page
        pagination.value.total = response.data.total
      })
    }

    const handleTableChange = (pagination: any) => {
      handleQueryContentList({
        page: pagination.current,
        size: pagination.pageSize
      })
    }

    const cancel = () => {
      imageUrl.value ='';
      modelVisible.value = false;
    }

    const handleModelOk = () => {
      content.value.status=(checked.value?'1':'0');
      console.log(content.value.pic);
      axios.post('/mall-content/content-Ms/saveContent',content.value).then(response=>{
        if(response.data.code==200){
          modelVisible.value=false;//关闭窗口
          message.info('操作成功');
          //加载最新品牌列表
          handleQueryContentList({
            page:pagination.value.current,
            size:pagination.value.pageSize
          });
        }else {
          message.info('操作失败');
          message.error(response.data.message);
        }
      })
    }

    const handleChange = (info:any) => {
      if (info.file.status ==='uploading'){
        Loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        Loading.value = false;
          content.value.pic = info.file.response;
      }
      if (info.file.status === 'error') {
        Loading.value = false;
        message.error('upload error');
      }
    };

    const beforeUpload = (file: File) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        message.error('Image must smaller than 10MB!');
      }
      return isJpgOrPng && isLt2M;
    };

    const findAllContentCategory = () => {
      axios.get('/mall-content/content-Ms/findAllContentCategory').then(response => {
        contentCategoryList.value = response.data
      })
    }

    const del = (id: number) =>  {
      axios.delete('/mall-content/content-Ms/deleteContent/' + id).then(response => {
        if (response.data.code == 200) {
          message.success('删除成功');
          //加载最新新闻列表
          handleQueryContentList({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        } else {
          message.error(response.data.message);
        }
      })
    };

    const edit = (record: any) => {
      modelVisible.value = true;
      // console.log("111" + record.id)
      // console.log("ss" + fileList.value)
      // console.log("222"+content.value.status)
      fileList.value=[];
      imageUrl.value=record.pic
      // console.log("record.pic"+record.pic)
      // record.pic=fileList.value;
      // imageUrl.value = record.pic;
      if (record.id != null) {
        checked.value = true;
      }
      content.value = Tool.copy(record); //复制对象到编辑模态框

      handleQueryContentList({
        page: 1,
        size: pagination.value.pageSize
      })
    }

    const add = () => {
      modelVisible.value = true;
      //初始化品牌对象
      fileList.value = [];
      content.value= {};
    }


    onMounted(() => {
      handleQueryContentList({
        page: 1,
        size: pagination.value.pageSize
      })
      findAllContentCategory();
    });

    return {
      contentList,
      columns,
      pagination,
      Loading,
      handleTableChange,
      del,
      add,
      modelVisible,
      handleModelOk,
      content,
      edit,
      contentCategoryList,
      findAllContentCategory,
      fileList,
      imageUrl,
      actionImg,
      handleChange,
      beforeUpload,
      checked,
      cancel,
    }

  }
}

</script>

<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>